import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hive_flutter/hive_flutter.dart';
import '../../shared/theme/app_theme.dart';
import 'user_extra_info_provider.dart';

class ThemeStageNotifier extends StateNotifier<StageTheme> {
  ThemeStageNotifier() : super(StageTheme.middle) {
    _load();
  }

  static const String _boxName = 'app';
  static const String _key = 'ui_stage_theme';
  static const String _autoSetKey = 'ui_stage_theme_auto_set';

  Future<void> _load() async {
    try {
      final box = Hive.box(_boxName);
      final String? saved = box.get(_key);
      final bool autoSet = box.get(_autoSetKey, defaultValue: false);
      
      if (saved != null) {
        state = _fromString(saved);
      } else if (!autoSet) {
        // 第一次使用，尝试根据用户年级自动设置主题
        await _autoSetThemeFromGrade();
      }
    } catch (_) {
      // ignore read errors, use default
    }
  }

  // 根据用户年级自动设置主题
  Future<void> _autoSetThemeFromGrade() async {
    try {
      final box = Hive.box(_boxName);
      final userData = box.get('userExtraInfo');
      
      if (userData != null) {
        final userInfo = Map<String, dynamic>.from(userData);
        final String? grade = userInfo['grade'] as String?;
        
        if (grade != null) {
          final StageTheme autoTheme = _getThemeFromGrade(grade);
          state = autoTheme;
          await box.put(_key, _toString(autoTheme));
          await box.put(_autoSetKey, true);
          print('🎨 根据年级自动设置主题: $grade -> ${_toString(autoTheme)}');
        }
      }
    } catch (e) {
      print('❌ 自动设置主题失败: $e');
    }
  }

  // 根据年级获取对应的主题
  StageTheme _getThemeFromGrade(String grade) {
    if (grade.contains('一年级') || grade.contains('二年级') || 
        grade.contains('三年级') || grade.contains('四年级') || 
        grade.contains('五年级') || grade.contains('六年级')) {
      return StageTheme.elementary;
    } else if (grade.contains('初一') || grade.contains('初二') || 
               grade.contains('初三')) {
      return StageTheme.middle;
    } else if (grade.contains('高一') || grade.contains('高二') || 
               grade.contains('高三')) {
      return StageTheme.high;
    }
    // 默认使用初中主题
    return StageTheme.middle;
  }

  Future<void> setStage(StageTheme stage) async {
    state = stage;
    try {
      final box = Hive.box(_boxName);
      await box.put(_key, _toString(stage));
      // 标记用户已经手动设置过主题
      await box.put(_autoSetKey, true);
    } catch (_) {
      // ignore write errors
    }
  }

  // 监听用户信息变化，如果用户信息更新且主题未手动设置过，则自动更新主题
  Future<void> onUserInfoChanged(UserExtraInfo? userInfo) async {
    try {
      final box = Hive.box(_boxName);
      final bool autoSet = box.get(_autoSetKey, defaultValue: false);
      
      // 只有在未手动设置过主题时才自动更新
      if (!autoSet && userInfo?.grade != null) {
        final StageTheme newTheme = _getThemeFromGrade(userInfo!.grade!);
        if (newTheme != state) {
          state = newTheme;
          await box.put(_key, _toString(newTheme));
          print('🎨 用户信息更新，自动调整主题: ${userInfo.grade} -> ${_toString(newTheme)}');
        }
      }
    } catch (e) {
      print('❌ 监听用户信息变化失败: $e');
    }
  }

  String _toString(StageTheme stage) {
    switch (stage) {
      case StageTheme.elementary:
        return 'elementary';
      case StageTheme.middle:
        return 'middle';
      case StageTheme.high:
        return 'high';
    }
  }

  StageTheme _fromString(String value) {
    switch (value) {
      case 'elementary':
        return StageTheme.elementary;
      case 'middle':
        return StageTheme.middle;
      case 'high':
        return StageTheme.high;
      default:
        return StageTheme.middle;
    }
  }
}

final themeStageProvider =
    StateNotifierProvider<ThemeStageNotifier, StageTheme>((ref) {
      return ThemeStageNotifier();
    });

// 组合Provider，用于协调用户信息和主题的联动
final themeUserInfoCoordinatorProvider = Provider<void>((ref) {
  final themeNotifier = ref.read(themeStageProvider.notifier);
  final userInfoNotifier = ref.read(userExtraInfoProvider.notifier);
  
  // 设置相互引用
  userInfoNotifier.setThemeNotifier(themeNotifier);
});

final themeDataProvider = Provider<ThemeData>((ref) {
  // 确保协调器被创建
  ref.watch(themeUserInfoCoordinatorProvider);
  
  final stage = ref.watch(themeStageProvider);
  final palette = ref.watch(accentPaletteProvider);
  return buildAppThemeForStage(stage, palette: palette);
});

class AccentPaletteNotifier extends StateNotifier<AccentPalette> {
  AccentPaletteNotifier() : super(AccentPalette.vibrant) {
    _load();
  }

  static const String _boxName = 'app';
  static const String _key = 'ui_accent_palette';

  Future<void> _load() async {
    try {
      final box = Hive.box(_boxName);
      final String? saved = box.get(_key);
      if (saved != null) {
        state = _fromString(saved);
      }
    } catch (_) {}
  }

  Future<void> setPalette(AccentPalette p) async {
    state = p;
    try {
      final box = Hive.box(_boxName);
      await box.put(_key, _toString(p));
    } catch (_) {}
  }

  String _toString(AccentPalette p) {
    switch (p) {
      case AccentPalette.vibrant:
        return 'vibrant';
      case AccentPalette.neon:
        return 'neon';
      case AccentPalette.candy:
        return 'candy';
    }
  }

  AccentPalette _fromString(String s) {
    switch (s) {
      case 'neon':
        return AccentPalette.neon;
      case 'candy':
        return AccentPalette.candy;
      case 'vibrant':
      default:
        return AccentPalette.vibrant;
    }
  }
}

final accentPaletteProvider =
    StateNotifierProvider<AccentPaletteNotifier, AccentPalette>((ref) {
      return AccentPaletteNotifier();
    });
